@echo off
cd /d "%~dp0"

rem Generate a header file with the exact current version using git tags.
rem This file is ran as a pre-build step for the sleepy and crashreport projects.

rem Find git

if not defined GIT for %%a in (git.exe) do if not [%%~$PATH:a] == [] set GIT="%%~$PATH:a"
if not defined GIT if exist "%ProgramFiles(x86)%\Git\bin\git.exe" set GIT="%ProgramFiles(x86)%\Git\bin\git.exe"
if not defined GIT if exist "%ProgramFiles%\Git\bin\git.exe" set GIT="%ProgramFiles%\Git\bin\git.exe"
if not defined GIT if exist "%ProgramW6432%\Git\bin\git.exe" set GIT="%ProgramW6432%\Git\bin\git.exe"
if not defined GIT if exist "%SystemDrive%\Git\bin\git.exe" set GIT="%SystemDrive%\Git\bin\git.exe"
if not defined GIT echo gen_version.bat: Can't find git! & exit /b 1

rem GitHub for Windows sets the GIT variable to the directory containing
rem git.exe, not git.exe itself. Detect and correct for this.

if exist "%GIT%git.exe" set GIT="%GIT%git.exe"
if exist "%GIT%\git.exe" set GIT="%GIT%\git.exe"

echo gen_version.bat: Found git at: %GIT%

rem Get git-describe output

echo // Auto-generated by gen_version.bat> version.h.tmp

for /f %%a in ('%GIT% describe --tags --dirty') do set VERSION=%%a
if errorlevel 1 exit /b 1
if [%VERSION%] == [] exit /b 1
echo #define VERSION "%VERSION:~1%">> version.h.tmp

rem Generate minor version numbers using the commit count and dirty flag
rem from the git-describe output. These are only used in file versions,
rem will be 0 for official releases, and are usually not visible to users.

set PATCH=0
for /f "tokens=2 delims=-" %%a in ("%VERSION%") do if not [%%a] == [dirty] set PATCH=%%a

set DIRTY=0
if "%VERSION:~-6%" == "-dirty" set DIRTY=1

echo #define VERSION_PATCH %PATCH% >> version.h.tmp
echo #define VERSION_DIRTY %DIRTY% >> version.h.tmp

rem Only update version.h if it changed, to avoid recompiling every time.

if not exist version.h goto write
fc version.h version.h.tmp > nul
if errorlevel 1 goto write
del version.h.tmp
goto :eof

:write
move /Y version.h.tmp version.h
goto :eof
